using System.IO;
using System.Timers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace MySqlBackUp.Server.Core {

    public static class ExecHelper
    {
        private static System.Timers.Timer _timer;
        private static bool _isRunning = false;

        public static void OpenConf()
        {
            var currPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "json");
            Process.Start(Path.Combine(currPath, ConfigHelper.ConfigFileName));
        }

        public static void Start()
        {
            _timer = new System.Timers.Timer();
            _timer.Interval = 1000 * 50;
            _timer.Elapsed += TimerOnElapsed;
            _timer.Enabled = true;
            _timer.Start();
            Console.WriteLine("定时任务已启动！");
            Task.Run(BackUp);
        }

        public static void Stop()
        {
            if (_timer==null || !_timer.Enabled) return;
            _timer.Stop();
            _timer.Enabled = false;
            _timer.Dispose();
            Console.WriteLine("定时任务已停止！");
        }

        public static void Reload()
        {
            Stop();
            Start();
        }

        private static void TimerOnElapsed(object sender, ElapsedEventArgs e)
        {
            if (_isRunning)
            {
                return;
            }
            var config = new ConfigHelper().Config;
            var now = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            if (now.Equals(config.NextExecDay + " " + config.ExecTime))
            {
                _isRunning = true;
                Task.Run(BackUp);
            }
        }

        private static void BackUp()
        {
            var path = Path.Combine(new ConfigHelper().Config.MySqlFolder, "mysqldump");
            var cmd = $"\"{path}\" -u{{userName}} -p{{password}} --databases {{database}} > {{path}}";
            foreach (var item in new ConfigHelper().Config.BackUpConfigs.Where(item => item.IsEnabled))
            {
                Console.WriteLine($"正在备份[{item.Database}]:");
                var itemCmd = cmd.Replace("{userName}", item.UserName)
                    .Replace("{password}", item.Password)
                    .Replace("{database}", item.Database)
                    .Replace("{path}", Path.Combine(item.SavePath, item.Database + DateTime.Now.ToString("yyyyMMddHHmmss") + ".sql"));
                RunCmd(itemCmd);
                Console.WriteLine($"备份完成");
            }
            var config = new ConfigHelper().Config;
            config.NextExecDay = DateTime.Parse(config.NextExecDay).AddDays(config.IntervalDay).ToString("yyyy-MM-dd");
            new ConfigHelper().SaveConfig(config);
            _isRunning = false;
        }

        private static void RunCmd(string cmdStr)
        {
            new CmdHelper(cmdStr).RunCmd();
        }
    }
}